using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Diagnostics;



namespace ERPStudio
{
    /// <summary>
    /// clasa de baza pentru toate machetele de tip card
    /// </summary>
    /// 
    public partial class FrmCard : ERPStudio.StudioForm
    {
        public event ValidatingAfterEndEditHandler HandlerValidatingAfterEndEdit;
        /// <summary>
        /// daca e setat pe true atunci la apasarea butoanelor de navigare
        /// se deplaseaza doar in prima Binding Source
        /// </summary>
        public Boolean MoveOnlyFirst = false;
        public SqlDataReader FormPropReader = null;
        public BindingSource cardBindingSource = null;

        
        [Browsable(true)]
        [Description("toolstrip")]
        public List<ToolStripButton> toolStripMainItems
        {
            get
            {
                /*_toolStripMainItems.Clear();
                foreach(ToolStripItem spi in _toolStripMain.Items)
                {
                    if(spi.GetType()== typeof(ToolStripButton))
                        _toolStripMainItems.Add((ToolStripButton)spi);
                }*/
                return _toolStripMainItems;
            }
            set
            {
                _toolStripMainItems = value;
                /*ToolStripButton[] array = new ToolStripButton[value.Count];
                _toolStripMainItems.CopyTo(array);
                _toolStripMain.Items.Clear();
                _toolStripMain.Items.AddRange(array);*/
            }
        }

        #region Functii din meniul principal    
        
        /// <summary>
        /// Functia apelata la apasarea butonului de salvare
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        /// 
        override public void Salvare(object sender, EventArgs args)
        {
            /// reseteaza numarul de inregistri adaugate
            NoRecAdded = 0;
            /// daca e doar in citire nu incercam sa salvam nimic
            if (ReadOnly)
                return;

            EroareSalvare = false;
            if (this.listBndSourceMain.Count == 0 || listTableAdaptor.Count == 0)
                throw new InvalidProgramException("nu sa adaugat nimic in lista de bindinguri(adaptoare) la FrmCard");
            if (listBndSourceMain.Count <= IndexSetCurent)
                throw new IndexOutOfRangeException();
            //if (listBndSourceMain[IndexSetCurent].Current == null && listBndSourceMain[IndexSetCurent].Count>0)
            //    throw new NullReferenceException("Nu exista inregistrare care sa poata fi salvata!");
            int cate = 0;
            SqlConnection conn = DeschideConexiune(workConnString);
            Object exObj = null;
            try
            {
                exObj = null;
                if (!Validate())
                {
                    EroareSalvare = true;
                    return;
                }
                foreach (BindingSource bs in listBndSourceMain)
                    bs.EndEdit();

                ValidatingAfterEndEditHandler tempH = HandlerValidatingAfterEndEdit;
                if (tempH != null)
                    if (!tempH(this))
                    {
                        EroareSalvare = true;
                        return;
                    }

                int IndexSet = 0;
                foreach(SqlDataAdapter sda in listTableAdaptor)
                {
                    InitAdapter(sda, conn, null);
                    DataTable _localDT = GetDataTable(IndexSet);
                    DataTable addRow = _localDT.GetChanges(DataRowState.Added);
                    if (addRow != null && addRow.Rows!=null)
                    {
                        NoRecAdded = addRow.Rows.Count;
                    }
                    exObj = _localDT.GetChanges();
                    cate += sda.Update(_localDT);

                    IndexSet++;
                }
                if (_DispalySaveStatus)
                {
                    if (cate != 0)
                        SetStatus("S-au salvat " + cate.ToString() + " inregistrari la: " + DateTime.Now.ToString());
                    else
                        SetStatus(String.Empty);
                }
                
                NoRecUpdated = cate;
            }
            catch (Exception ex)
            {
                TrateazaExceptie(ex,ex.Data);
                EroareSalvare = true;
            }
            finally
            {
                InchideConexiune(conn);
            }
            SetTitle();
        }

        /// <summary>
        /// event pentru AddNew la Bindings
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        public void Adauga(object sender, EventArgs args)
        {
            ///optiune pentru a bloca adaugarea de randuri noi in orice BS
            if (!this._AllowAddRow)
                return;
            if (ReadOnly)
            {
                MessageBox.Show("Macheta este deschisa doar in consultare!",
                    "Eroare",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                return;
            }
            Trace.Assert(listBndSourceMain.Count != 0, "listBndSourceMain nu s-a populat!!!");
            if (listBndSourceMain.Count <= IndexSetCurent)
                throw new IndexOutOfRangeException();

            if (!this.listBndSourceMain[IndexSetCurent].AllowNew)
                return;

            try
            {
                this.listBndSourceMain[IndexSetCurent].AddNew();
                DupaAdauga(0);
            }
            catch (Exception ex)
            {
                TrateazaExceptie(ex);
            } 
            SetTitle();
        }

        public void Primul(object sender, EventArgs args)
        {
            Trace.Assert(listBndSourceMain.Count != 0, "listBndSourceMain nu s-a populat!!!");
            if (!SalvareLocal()) return;
            if (listBndSourceMain.Count <= IndexSetCurent)
                throw new IndexOutOfRangeException();
            try
            {
                if (MoveOnlyFirst)
                    this.listBndSourceMain[0].MoveFirst();
                else
                    this.listBndSourceMain[IndexSetCurent].MoveFirst();
            }
            catch (Exception ex)
            {
                TrateazaExceptie(ex);
            }
            SetTitle();

        }

        public void Urmator(object sender, EventArgs args)
        {
            Trace.Assert(listBndSourceMain.Count != 0, "listBndSourceMain nu s-a populat!!!");
            if (!SalvareLocal()) return;
            if (listBndSourceMain.Count <= IndexSetCurent)
                throw new IndexOutOfRangeException();
            try
            {
                if (MoveOnlyFirst)
                    listBndSourceMain[0].MoveNext();
                else
                    listBndSourceMain[IndexSetCurent].MoveNext();
            }
            catch (Exception ex)
            {
                TrateazaExceptie(ex);
            }
            SetTitle();
        }
        public void Anterior(object sender, EventArgs args)
        {
            Trace.Assert(listBndSourceMain.Count != 0, "listBndSourceMain nu s-a populat!!!");
            if (!SalvareLocal()) return;
            if (listBndSourceMain.Count <= IndexSetCurent)
                throw new IndexOutOfRangeException();
            try
            {
                if (MoveOnlyFirst)
                    this.listBndSourceMain[0].MovePrevious();
                else
                    this.listBndSourceMain[IndexSetCurent].MovePrevious();
            }
            catch (Exception ex)
            {
                TrateazaExceptie(ex);
            }
            SetTitle();
        }
        public void Ultimul(object sender, EventArgs args)
        {
            Trace.Assert(listBndSourceMain.Count != 0, "listBndSourceMain nu s-a populat!!!");
            if (!SalvareLocal()) return;
            if (listBndSourceMain.Count <= IndexSetCurent)
                throw new IndexOutOfRangeException();
            try
            {
                if (MoveOnlyFirst)
                    this.listBndSourceMain[0].MoveLast();
                else
                    this.listBndSourceMain[IndexSetCurent].MoveLast();
            }
            catch (Exception ex)
            {
                TrateazaExceptie(ex);
            }
            SetTitle();
            //UpdateBounds();
        }

        public void Sterge(object sender, EventArgs args)
        {
            if (ReadOnly)
            {
                MessageBox.Show("Macheta este deschisa doar in consultare!",
                    "Eroare",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                return;
            }
            if (MessageBox.Show("Sunteti sigur ca doriti eliminarea inregistrarii curente?",
                    "Verificare",
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Question) == DialogResult.No)
                return;
            try
            {
                Boolean saSters = false;
                if (gridRezumat != null)
                {
                    foreach (DataGridView dgv in gridRezumat)
                    {
                        if (dgv.ContainsFocus)
                        {
                            ((BindingSource)dgv.DataSource).RemoveCurrent();
                            saSters = true;
                            break;
                        }
                    }
                }
                if (!saSters)
                {
                    if (listBndSourceMain.Count <= IndexSetCurent)
                        throw new IndexOutOfRangeException();
                    if (this.listBndSourceMain[IndexSetCurent].Current == null)
                        return;
                    this.listBndSourceMain[IndexSetCurent].RemoveCurrent();
                }

            }
            catch (Exception ex)
            {
                TrateazaExceptie(ex);
            }
            Update();
            SetTitle();

        }
        #endregion
        
        private List<System.Windows.Forms.Label> tabLabel = new List<Label>();
        private List<System.Windows.Forms.TextBox> tabTextBox = new List<TextBox>();
        private List<System.Windows.Forms.CheckBox> tabCheckBox = new List<CheckBox>();

        public FrmCard(ModuleClass mInfo)
            : base(mInfo)
        {
            InitializeComponent();
            if (mInfo != null && mInfo.CurrentTheme == "tribunal")
                return;
            HandleMoveFirst += new EventHandler(Primul);
            HandleMoveLast += new EventHandler(Ultimul);
            HandleMoveNext += new EventHandler(Urmator);
            HandleMovePrev += new EventHandler(Anterior);
            HandleAdd += new EventHandler(Adauga);
            HandleDel += new EventHandler(Sterge);
            HandleSearch += new EventHandler(Cauta);

           
        }

        /// <summary>
        /// doar pentru designer
        /// </summary>
        protected FrmCard()
            : this(null)
        {
           
        }

        private void FrmCard_Load(object sender, EventArgs e)
        {
            numeMacheta = Text;
        }

        private void FrmCard_FormClosing(object sender, FormClosingEventArgs e)
        {
            if(_CloseFormList.Count!=0)
            {
                foreach (Form frm in _CloseFormList)
                    frm.Close();
            }
            //daca e doar in citire nu mai verificam nimic
            if (listBndSourceMain.Count > 0)
            {
                currentRow = ((DataRowView)listBndSourceMain[0].Current);
            }
            if (ReadOnly)
                return;
            try
            {
                foreach (BindingSource bs in this.listBndSourceMain)
                {
                    bs.EndEdit();
                }
            }
            catch (Exception ex)
            {
                // nu e eroare 
                if (!TrateazaExceptie(ex))
                {
                    e.Cancel = true;
                    return;
                }
                else
                {
                    e.Cancel = false;
                    return;
                }
            }

            DataTable _localDT = GetDataTable(0);
            if (_localDT != null)
            {
                //DataSet modificari = _localDT.DataSet.GetChanges();
                DataTable modificari = _localDT.GetChanges();
                Boolean eMod = false;
                String mod = String.Empty;
                if (modificari != null)
                {
                    foreach (DataRow dr in modificari.Rows)
                    {
                        if (dr.HasVersion(DataRowVersion.Original))
                        {


                            for (int i = 0; i < modificari.Columns.Count; i++)
                            {
                                if (dr[i, DataRowVersion.Original].ToString() != dr[i, DataRowVersion.Current].ToString())
                                {
                                    mod += modificari.Columns[i].ColumnName + ",";
                                    eMod = true;
                                }
                            }
                        }
                    }
                    if (eMod)
                    {
                        if (MessageBox.Show("Renuntati la modificarile efectuate pana acum?(" + mod + ")", "Avertisment",
                            MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
                        {
                            e.Cancel = true;
                        }
                    }
                }
            }

        }

        private void FrmCard_Shown(object sender, EventArgs e)
        {
            ///se apeleaza dupa setarea binding source
            SetTitle();
        }
    }
}